<?php

namespace App\Models;


use Illuminate\Support\Facades\DB;

class Setting extends Common
{
    protected $table = 'my_setting';
    protected $primaryKey = 'setting_id';

    public function settingFind($key = '')
    {
        if (empty($key)) return [];
        $exist = $this->getCount(['key'=>$key]);
        if ($exist){
            $field_path = app_path() . '/setting/' . $key .'.json';
            if (!file_exists($field_path)){
                file_put_contents($field_path, json_encode([$key=>'']));
            }
            $json_data = file_get_contents($field_path);
            $data = json_decode($json_data, true);
            return (object)$data[$key];
        }
        return [];
    }

    public function insetSetting($key = '', $val = [])
    {
        if (empty($key) || empty($val)) return false;
        $exist = $this->getCount(['key'=>$key]);
        if ($exist){
            $rows = DB::table($this->table)->where('key', $key)->update(['val'=>json_encode($val)]);
            if (empty($rows)){
                return false;
            }
        }else{
            $rows = DB::table($this->table)->insert(['key'=>$key,'val'=>json_encode($val)]);
            if (empty($rows)){
                return false;
            }
        }
        $field_path = app_path() . '/setting/' . $key .'.json';
        file_put_contents($field_path, json_encode([$key=>$val]));
        return true;
    }

    /**
     * 极光信息推送
     * @param $alert
     * @param $alias
     * @param array $extras
     * @param string $app_type
     * @return bool
     */
    public function ruleExec($alert, $alias, $extras = [], $app_type = '')
    {
        try{
            // import('push.api.Push');
            $setting_model = new Setting();
            $setting_data = $setting_model->settingFind('push' . $app_type);
            if (empty($setting_data)){
                return false;
            }
            // $push = new \Push($setting_data['app_key'], $setting_data['master_secret']);
            $ios_notification = [
                'alert' => $alert,
                'badge' => '+1',
                'extras'=>$extras
            ];
            $android_notification = [
                'alert'=>$alert,
                'title'=>$extras['contents'],
                'extras'=>$extras
            ];
            // if (empty($setting_data['environment'])){
            //     $push->develop($alert, $alias, $ios_notification, $android_notification);
            // }else{
            //     $push->production($alert, $alias, $ios_notification, $android_notification);
            // }
        } catch(\Exception $e){

        }
        return true;
    }

    /**
     * 获取access_token信息
     * @param $token_type
     * @return mixed|string
     */
    public function getAccessToken($token_type = 'applet')
    {
        $setting_data = $this->settingFind($token_type);
        if (empty($setting_data->access_token)){
            $access_token = $this->accessToken();
            $this->insetSetting($token_type, ['access_token'=>$access_token,'last_time'=>time()]);
        }else{
            if (time() - $setting_data->last_time > 7000){
                $access_token = $this->accessToken();
                $this->insetSetting($token_type, ['access_token'=>$access_token,'last_time'=>time()]);
            }else{
                $access_token = $setting_data['access_token'];
            }
        }
        return $access_token;
    }

    private function accessToken()
    {
        $setting_data = $this->settingFind('wx_applet');
        if (empty($setting_data->app_id) || empty($setting_data->app_key)){
            return '';
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential';
        $url .= '&appid=' . $setting_data['app_id'] . '&secret=' . $setting_data['app_key'];
        $data = file_get_contents($url);
        $json_data = json_decode($data, true);
        if (empty($json_data['access_token'])){
            return '';
        }
        return $json_data['access_token'];
    }

}
